import base64
from io import BytesIO

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox, QInputDialog, QLineEdit
import sys
import os

from PIL import Image
import matplotlib.pyplot as plt
from Date import memory_pic
from XmindToExcel import XmindToExcel

XmindToExcel = XmindToExcel()

from Tools import Tools

Tools = Tools()


class Ui_MainWindow(object):


    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(850, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        #
        self.label_XmindFile = QtWidgets.QLabel(self.centralwidget)
        self.label_XmindFile.setGeometry(QtCore.QRect(10, 10, 101, 41))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label_XmindFile.setFont(font)
        self.label_XmindFile.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.label_XmindFile.setAlignment(QtCore.Qt.AlignCenter)
        self.label_XmindFile.setObjectName("label_XmindFile")

        #
        self.label_ExcelFile = QtWidgets.QLabel(self.centralwidget)
        self.label_ExcelFile.setGeometry(QtCore.QRect(10, 50, 101, 41))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label_ExcelFile.setFont(font)
        self.label_ExcelFile.setAlignment(QtCore.Qt.AlignCenter)
        self.label_ExcelFile.setObjectName("label_ExcelFile")


        self.textEdit_XmindFileAddr = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit_XmindFileAddr.setGeometry(QtCore.QRect(120, 10, 551, 31))
        self.textEdit_XmindFileAddr.setObjectName("textEdit_XmindFileAddr")


        self.textEdit_EXCLFileAddr = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit_EXCLFileAddr.setGeometry(QtCore.QRect(120, 60, 551, 31))
        self.textEdit_EXCLFileAddr.setObjectName("textEdit_EXCLFileAddr")


        self.toolButton_SelectXMLFileAddr = QtWidgets.QToolButton(self.centralwidget)
        self.toolButton_SelectXMLFileAddr.setGeometry(QtCore.QRect(680, 10, 61, 31))
        self.toolButton_SelectXMLFileAddr.setObjectName("toolButton_SelectXMLFileAddr")

        self.toolButton_SelectXMLFileAddr.clicked.connect(self.selectDirOrFileOfXmind)


        self.toolButton_SelectEXCLFileAddr = QtWidgets.QToolButton(self.centralwidget)
        self.toolButton_SelectEXCLFileAddr.setGeometry(QtCore.QRect(680, 60, 61, 31))
        self.toolButton_SelectEXCLFileAddr.setObjectName("toolButton_SelectEXCLFileAddr")

        self.toolButton_SelectEXCLFileAddr.clicked.connect(self.inputDirAddr)


        self.pushButton_ResetXMFile = QtWidgets.QToolButton(self.centralwidget)
        self.pushButton_ResetXMFile.setGeometry(QtCore.QRect(760, 10, 61, 31))
        self.pushButton_ResetXMFile.setObjectName("pushButton_ResetXMFile")

        self.pushButton_ResetXMFile.clicked.connect(lambda:self.textEdit_XmindFileAddr.clear())


        self.pushButton_ResetEXCLFile = QtWidgets.QToolButton(self.centralwidget)
        self.pushButton_ResetEXCLFile.setGeometry(QtCore.QRect(760, 60, 61, 31))
        self.pushButton_ResetEXCLFile.setObjectName("pushButton_ResetEXCLFile")

        self.pushButton_ResetEXCLFile.clicked.connect(lambda:self.textEdit_EXCLFileAddr.clear())


        self.textBrowser_LogScence = QtWidgets.QTextBrowser(self.centralwidget)
        self.textBrowser_LogScence.setGeometry(QtCore.QRect(60, 110, 730, 341))
        self.textBrowser_LogScence.setObjectName("textBrowser_LogScence")

        self.pushButton_XML2EXCL = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_XML2EXCL.setGeometry(QtCore.QRect(310, 490, 151, 61))
        self.pushButton_XML2EXCL.setObjectName("pushButton_XML2EXCL")

        self.pushButton_XML2EXCL.clicked.connect(self.fun_Xmind2Excel)


        self.pushButton_ExampleXmind = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_ExampleXmind.setGeometry(QtCore.QRect(600, 470, 161, 41))
        self.pushButton_ExampleXmind.setObjectName("pushButton_ExampleXmind")

        self.pushButton_ExampleXmind.clicked.connect(self.ShowTheExample)


        self.pushButton_QuitWindow = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_QuitWindow.setGeometry(QtCore.QRect(600, 520, 161, 41))
        self.pushButton_QuitWindow.setObjectName("pushButton_QuitWindow")

        self.pushButton_QuitWindow.clicked.connect(self.sovle_close)

        self.checkBox_XmindDir = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox_XmindDir.setGeometry(QtCore.QRect(700, 40, 121, 20))
        self.checkBox_XmindDir.setObjectName("checkBox_XmindDir")


        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)



    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "XMind转换Excel工具"))
        self.label_XmindFile.setText(_translate("MainWindow", "Xmind 文件"))
        self.label_ExcelFile.setText(_translate("MainWindow", "Excel 文件"))
        self.toolButton_SelectXMLFileAddr.setText(_translate("MainWindow", "选择"))
        self.toolButton_SelectEXCLFileAddr.setText(_translate("MainWindow", "选择"))
        self.pushButton_XML2EXCL.setText(_translate("MainWindow", "Xmind 转换 Excel"))
        self.pushButton_ExampleXmind.setText(_translate("MainWindow", "XMind标准示例"))
        self.pushButton_QuitWindow.setText(_translate("MainWindow", "退出"))
        self.pushButton_ResetXMFile.setText(_translate("MainWindow", "重置"))
        self.pushButton_ResetEXCLFile.setText(_translate("MainWindow", "重置"))
        self.checkBox_XmindDir.setText(_translate("MainWindow", "批量转换"))

    def selectDirOrFileOfXmind(self):
        # value, ok = QInputDialog.getText(self, "请选择[文件夹批量转换]还是[文件单独转换]", "文件夹批量转换请输入[Y],文件单独转换请选择[N]:", QLineEdit.Normal, "Y")
        # if value == 'Y' or value == 'y':
        #     self.inputXmindDirPath()
        # elif value == 'N' or value == 'n':
        #     self.inputXmindFilePath()
        # else:
        #     QMessageBox.critical(None, '错误', '请输入[Y]或[N],不要输入其他字符')
        if self.checkBox_XmindDir.isChecked():
            self.inputXmindDirPath()
        else:
            self.inputXmindFilePath()
        
            




    def inputXmindDirPath(self):
        path = []
        #fileName,fileType = QtWidgets.QFileDialog.getOpenFileName(self,"选取文件",os.getcwd(),";Text Files(*.xmind)")
        fileName= QtWidgets.QFileDialog.getExistingDirectory(self, "请选择文件夹路径", os.getcwd())
        #fileName = QtWidgets.QFileDialog.getOpenFileNames(self,"选取文件",os.getcwd(),";Text Files(*.xmind)")
        path.append(fileName)
        self.textEdit_XmindFileAddr.setText(fileName)
    
    def inputXmindFilePath(self):
        path = []
        fileName,fileType = QtWidgets.QFileDialog.getOpenFileName(self,"选取文件",os.getcwd(),";Text Files(*.xmind)")
        #fileName= QtWidgets.QFileDialog.getExistingDirectory(self, "请选择文件夹路径", os.getcwd())
        #fileName = QtWidgets.QFileDialog.getOpenFileNames(self,"选取文件",os.getcwd(),";Text Files(*.xmind)")
        path.append(fileName)
        self.textEdit_XmindFileAddr.setText(fileName)

    def inputDirAddr(self):
        path = []
        fileName= QtWidgets.QFileDialog.getExistingDirectory(self, "请选择文件夹路径", os.getcwd())
        path.append(fileName)
        self.textEdit_EXCLFileAddr.setText(fileName)

    
    
    #XmindToExcel = XmindToExcel()
    def fun_Xmind2Excel(self):
        try:
            self.printf("XMind源文件路径:"+self.textEdit_XmindFileAddr.toPlainText())
            if self.textEdit_EXCLFileAddr.toPlainText() == '':
                self.printf("Excel文件存储路径:"+os.path.split(self.textEdit_XmindFileAddr.toPlainText())[0])
            else:
                self.printf("Excel文件存储路径:"+self.textEdit_EXCLFileAddr.toPlainText())
            XmindPath = self.textEdit_XmindFileAddr.toPlainText()
            ExcelPath = self.textEdit_EXCLFileAddr.toPlainText()
            if ExcelPath == '':
                if os.path.isdir(XmindPath):
                    ExcelPath = XmindPath
                elif os.path.isfile(XmindPath):
                    ExcelPath = os.path.split(XmindPath)[0]
            elif not os.path.exists(ExcelPath):
                QMessageBox.critical(None, '错误', '目标路径不存在,请重新选择')
                self.textEdit_EXCLFileAddr.clear()

            if os.path.isdir(XmindPath):
                flag = 0
                for XmindFileName in os.listdir(XmindPath):
                    if os.path.splitext(XmindFileName)[1] in '.xmind':
                        flag = 1
                        xmind_file_path = str(Tools.get_OSInfo(XmindPath + '/' + XmindFileName))
                        print(f'当前正在导出的xmind文件路径为：{xmind_file_path}')
                        out_dir = str(Tools.get_OSInfo(ExcelPath))
                        print(f'导出目录为：{out_dir}')
                        X2ELog = XmindToExcel.transfer_xmind_case(xmind_file_path, out_dir)
                        if X2ELog['success']:
                            item1 = "导出结果： success"
                            item2 = f"导出case文件路径：{X2ELog['data']['case_path']}"
                            item3 = X2ELog['data']["error_log"]
                            item4 = "\n"
                        else:
                            item1 = "导出结果： 有部分失败\n错误如下"
                            item2 = f"导出case文件路径：{X2ELog['data']['case_path']}"
                            item3 = X2ELog['data']["error_log"]
                            item4 = f"本地错误日志名称：{X2ELog['data']['error_log_name']}"
                        self.qList = [item1, item2, *item3, item4]
                        for item in self.qList:
                            self.printf(item)
                        QMessageBox.information(None, '转换完成', f'{os.path.split(item2)[1]}转换完成')
                    else:
                        QMessageBox.information(None, '转换完成', '文件夹内所有文件转换完成')
                if flag != 1:
                    QMessageBox.critical(None, '此文件夹内无[XMind]格式文件', '请重新选择有[XMind]格式文件的文件夹')
                    self.textEdit_XmindFileAddr.clear()

            else:
                #try:
                    #self.printf(os.path.splitext(XmindPath)[1])
                if os.path.splitext(XmindPath)[1] == '.xmind':
                    print("转换后的路径:"+str(Tools.get_OSInfo(ExcelPath)))
                    X2ELog = XmindToExcel.transfer_xmind_case(str(Tools.get_OSInfo(XmindPath)),str(Tools.get_OSInfo(ExcelPath)))
                    if X2ELog['success']:
                        item1 = "导出结果： success"
                        item2 = f"导出case文件路径：{X2ELog['data']['case_path']}"
                        item3 = X2ELog['data']["error_log"]
                        item4 = "\n"
                    else:
                        item1 = "导出结果： 有部分失败\n错误如下"
                        item2 = f"导出case文件路径：{X2ELog['data']['case_path']}"
                        item3 = X2ELog['data']["error_log"]
                        item4 = f"本地错误日志名称：{X2ELog['data']['error_log_name']}"
                    self.qList = [item1, item2, *item3, item4]
                    for item in self.qList:
                        self.printf(item)
                    QMessageBox.information(None, '转换完成', str(os.path.split(XmindPath)[1])+'文件转换完成')
                else:
                    QMessageBox.critical(None, '您输入的不是[XMind]格式的文件', '请重新输入[XMind]格式文件或文件夹的路径')
                    self.textEdit_XmindFileAddr.clear()

                    print(UnboundLocalError)
                    QMessageBox.critical(None, '您输入的不是[XMind]格式的文件', '请重新输入[XMind]格式文件或文件夹的路径')
                    self.textEdit_XmindFileAddr.clear()
        except Exception as e:
            print(f'转换报错，错误为：{e}')


    def printf(self,mes):
        self.textBrowser_LogScence.append(str(mes))   
        self.cursot = self.textBrowser_LogScence.textCursor()
        self.textBrowser_LogScence.moveCursor(self.cursot.End)
        QtWidgets.QApplication.processEvents()


    def ShowTheExample(self):
        # img=Image.open(Tools.get_OSInfo(os.getcwd()+'/Date/ExampleXmind.png'))
        # plt.figure("Example for XMIND")
        # plt.imshow(img)
        # plt.show()
        ExampleXmind_pic = base64.b64decode(memory_pic.ExampleXmind_png)
        by = BytesIO()
        by.write(ExampleXmind_pic)
        img = Image.open(by)
        # self.f = open('ExampleXmind.png','wb')
        # self.f.write(ExampleXmind_pic)
        # img=Image.open('ExampleXmind.png')
        plt.figure("Example for XMIND")
        plt.imshow(img)
        print('执行关闭')
        by.close()
        plt.show()

        
    def sovle_close(self):
        try:
            self.pic_handler.close()
        except Exception:
            pass
        finally:
            self.close()



    # def dragEnterEvent(self, evn):
    #     self.setWindowTitle('鼠标拖入窗口了')
    #     self.textEdit_XmindFileAddr(evn.mimeData().text())
    #     evn.accept()
    

    # def dropEvent(self, evn):
    #     self.setWindowTitle('鼠标放开了')


    # def dragMoveEvent(self, evn):
    #     print('鼠标移入')
